<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Changer:  
 * Datetime: 2023年07月18日18:09:54
 */

namespace App\Http\Model;


use App\Http\Services\CommonServices;
use App\Http\Services\UserFilterServices;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use phpDocumentor\Reflection\Types\Self_;

class KovStatic extends Base
{
    protected $table = "kov_statistics";


    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 插入数据
     * @param array $inset
     * @return bool
     */
    public function checkAndInsert($inset = [])
    {
        DB::beginTransaction();
        try {
            DB::table($this->table)->insert($inset);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
        return true;
    }

    /**
     * 更新用户数据
     * @param array $update
     * @param $uuid
     * @return bool
     */
    public function UpdateData($update = [])
    {
        DB::beginTransaction();
        try {
            $this->updateBatch('zb_'.$this->table,$update);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
        return true;
    }

    /**
     * 批量更新
     * @param string $tableName
     * @param array $multipleData
     * @return bool|int
     */
    public function updateBatch($tableName = "", $multipleData = array())
    {

        if ($tableName && !empty($multipleData)) {

            // column or fields to update
            $updateColumn = array_keys($multipleData[0]);
            $referenceColumn = $updateColumn[0]; //e.g id
            unset($updateColumn[0]);
            $whereIn = "";

            $q = "UPDATE " . $tableName . " SET ";
            foreach ($updateColumn as $uColumn) {
                $q .= $uColumn . " = CASE ";

                foreach ($multipleData as $data) {
                    $q .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' ";
                }
                $q .= "ELSE " . $uColumn . " END, ";
            }
            foreach ($multipleData as $data) {
                $whereIn .= "'" . $data[$referenceColumn] . "', ";
            }
            $q = rtrim($q, ", ") . " WHERE " . $referenceColumn . " IN (" . rtrim($whereIn, ', ') . ")";

            // Update
            return DB::update(DB::raw($q));

        } else {
            return false;
        }

    }
}

